package sdk

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

//
type Client struct {
	httpClient *http.Client
	serverUrl  string
	partner    []byte
	key        []byte
}

// 实例化一个新客户端
func NewClient(serverUrl string, partner []byte, key []byte) (client *Client, err error) {
	client = &Client{}
	client.httpClient = &http.Client{}
	client.serverUrl = serverUrl
	client.partner = partner
	client.key = key
	return client, nil
}

// 干活
func (client *Client) DoAction(request IRequest, response IResponse) (err error) {
	requestJson, err := json.Marshal(request)
	if err != nil {
		panic(err)
	}

	obj := make(map[string]interface{})
	//err = json.Unmarshal(requestJson, &obj)
	obj["timestamp"] = time.Now().Format("2006-01-02 15:04:05")
	fmt.Println(obj)
	obj["partner"] = string(client.partner)
	obj["params"] = string(requestJson)
	jsonStr, err := json.Marshal(obj)
	if err != nil {
		panic(err)
	}
	fmt.Println("jsonStr=", string(jsonStr))

	//
	sign, err := GetSign(jsonStr, client.key)
	if err != nil {
		panic(err)
	}
	fmt.Println("sign=", string(sign))

	url := client.serverUrl + request.GetMethod()
	req, err := http.NewRequest(
		"POST",                             //method string,
		url,                                //url string,
		strings.NewReader(string(jsonStr)), //body io.Reader,
	)
	if err != nil {
		panic(err)
	}
	req.Header.Set("sign", string(sign))
	req.Header.Set("Content-Type", "application/json; charset=utf-8")
	res, err := client.httpClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(body))
	err = json.Unmarshal(
		body,     // data []byte,
		response, // v interface{},
	)
	if err != nil {
		panic(err)
	}
	return
}
